import os
from pathlib import Path
import logging

from fastapi import FastAPI, Request, UploadFile, Form, BackgroundTasks
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

from backend.tasks import process_document
from backend.utils import save_upload_file, allowed_file, settings, load_prompt_list

# 日志配置
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 基准路径
BASE_DIR = Path(__file__).resolve().parent.parent
# 绝对路径指向 frontend/templates
templates = Jinja2Templates(directory=str(BASE_DIR / "frontend" / "templates"))

app = FastAPI()
app.mount("/static", StaticFiles(directory=str(BASE_DIR / "frontend" / "static")), name="static")

UPLOAD_DIR = Path("/tmp/uploads")

@app.get('/', response_class=HTMLResponse)
async def index(request: Request):
    # 动态获取支持的文档类型
    prompt_list = load_prompt_list()
    return templates.TemplateResponse(
        "index.html",
        {"request": request, "prompt_list": prompt_list}
    )

@app.post('/submit')
async def submit(
    request: Request,
    background_tasks: BackgroundTasks,
    email: str = Form(...),
    doc_name: str = Form(...),
    file: UploadFile = Form(...)
):
    if not allowed_file(file.filename):
        return JSONResponse({"error": "不支持的文件类型"}, status_code=400)
    contents = await file.read()
    if len(contents) > settings.max_file_size * 1024 * 1024:
        return JSONResponse({"error": "文件超过大小限制"}, status_code=400)
    file.file.seek(0)
    saved_path = save_upload_file(file, UPLOAD_DIR)
    background_tasks.add_task(process_document.delay, str(saved_path), file.filename, email, doc_name)
    logger.info(f"Received document {file.filename} from {email}, queued for processing.")
    return JSONResponse({"message": "文档已提交，处理完成后将发送邮件通知。"})